import { useDebounceFn, useSetState } from 'ahooks';
import { Button, DatePicker, Form, Popconfirm, Select, message } from 'antd';
import * as echarts from 'echarts';
import _ from 'lodash';
import moment from 'moment';
import React, { useEffect, useState } from 'react';
import { connect } from 'umi';
import styles from './index.less';

import { TRDefault, TRMessage } from '#/components/index.js';
import { CaretLeftOutlined, CaretRightOutlined, UploadOutlined } from '#/utils/antdIcons.js';
import { HttpCode } from '#/utils/contacts.js';
import Title from './components/Title/index.jsx';

import { DimensionalSort, PageLoading, Pointer } from '@/components/index.js';
import { useRem } from '@/hooks/index.js';
import { TjStation } from '@/pages/ETrade/components/index.js';
import { export_json_to_excel } from '@/utils/fileExport.js';

import BaseTable from './components/BaseTable';
import { ChartDealIncome, ChartDealPrice, ChartDealTariff } from './components/Charts/index.js';
import TjSequenceSelect from './components/TjSequenceSelect';
import { OPTION_KEY, SELECT_DATA, headerMap, tableHead } from './helper';
import {
  getDynamicColumns,
  getTimeTradeData,
  queryMarketList,
  querySpotResumeAnalysisDetail,
} from './services.js';
import { formatJson, pointConvert } from './utils.js';
// @ts-ignore
import { getTreeByCodes } from '@/utils';

const { RangePicker } = DatePicker;
const monthFormat = 'YYYYMMDD';
let dataInit: moment.Moment[] = [];
// 设置日期范围为当前月份
dataInit = [moment().startOf('month'), moment()];

const NewMediumlongTermResetting = ({ menuCode, buttonPermissions }: any) => {
  const [loading, setLoading] = useState(true),
    [error, setError] = useState(''),
    [listLoading, setListLoading] = useState(false),
    [columns, setColumns] = useState([]),
    [tableData, setTableData] = useState({}),
    [tableDataSource, setTableDataSource] = useState([]), //主表格数据
    [tableHeader, setTableHeader]: any = useState(), //表头
    [stations, setStations] = useState<any>([]), // 全部场站（平铺）
    [stationTree, setStationTree] = useState<any>([]), // 已选省份的场站树
    [optionAll, setOptionAll] = useState<any>([]), //所选省份全部场站(全选)
    [param, setParam] = useState(SELECT_DATA), //灵活聚合项
    [form] = Form.useForm(),
    reSize = useRem(1920),
    [userList, setUserList] = useState<any>([]),
    [echartsTariffData, setEchartsTariffData] = useState<any>({}), //偏差电费组成
    [echartsIncomeData, setEchartsIncomeData] = useState<any>({}), //综合扣费收入
    [echartsPriceData, setEchartsPriceData] = useState<any>({}), //综合扣费电价
    [echartsParam, setEchartsParam]: any = useState(), //图表筛选参数
    [filterUnitOptions, setFilterUnitOptions] = useState(), //父维度筛选 交易单元列表
    [dateTime, setDateTime] = useState<any>(), //父维度筛选 时间
    [regions, setRegions] = useState<any[]>([]), // 全部省份
    [isFullScreenEcharts, setIsFullScreenEcharts] = useState(false), // 是否为图表全屏展示
    [isFullScreenTable, setIsFullScreenTable] = useState(false), // 是否为表格全屏展示
    [visible, setVisible] = useState(false), // 控制大数据查询前提示
    [issueStatusOption, setIssueStatusOption] = useState<any>([]), //时序状态
    [exportParam, setExportParam] = useSetState({
      dateRange: [],
    }),
    [state, setState] = useSetState<any>({
      refData: [],
      showModal: false,
      filterList: [],
    }),
    [regionCode, setRegionCode] = useState<any>(''),
    [provinceId, setProvinceId] = useState(''),
    [timeOptions, setTimeOptions] = useState<any>([]),
    [noTimeOptions, setNoTimeOptions] = useState<any>([]),
    [selectTimeOptions, setSelectTimeOptions] = useState<any>([]),
    [reTime, setReTime] = useState<any>(),
    [allContractTypes, setAllContractTypes] = useState<any>([]),
    [formValues, setFormValues] = useState({
      date: dataInit,
      unit: [],
      tag: '1',
    }),
    [sumaryData, setSumaryData] = useState([]);

  React.useEffect(() => {
    init();
  }, []);

  /** handle data */
  async function init() {
    // 获取数据权限
    setLoading(true);
    setTimeOptions([]);
    setNoTimeOptions([]);
    setSumaryData([]);
    const res = await queryMarketList(menuCode);
    if (res?.statusCode === HttpCode.SUCCESS) {
      const power = getTreeByCodes(['market', 'group', 'station'], res.json).treeOptions;
      initDataPower(power);
    } else {
      setError('系统异常');
    }
    setLoading(false);
  }

  // 概览数据
  async function onFetchSumarys(data: any) {
    if (data) {
      setSumaryData(data);
    } else {
      setError('系统异常');
    }
  }

  //获取省份对应交易单元
  const getStationOptions = (data: any) => {
    const _optionAll: any = _.flatten(
      data?.map((i: any) => i?.children?.map((y: any) => y.stationId)),
    );
    setOptionAll(_optionAll);
    setStationTree(data);
    form.setFieldsValue({
      unit: _optionAll,
    });
    return _optionAll;
  };

  const _onFinish = useDebounceFn(
    (values: any) => {
      setExportParam({
        dateRange: values.date,
      });
      // 查询数据
      const _formData: any = values,
        _date = _formData.date,
        _startDate = _date && moment(_date[0]).format('YYYY-MM-DD'),
        _endDate = _date && moment(_date[1]).format('YYYY-MM-DD'),
        _pointNum = _formData.point,
        _issueStatus = _formData.issueStatus,
        _tag = _formData.tag,
        _unit = _formData.unit,
        _param = [SELECT_DATA[0], SELECT_DATA[1]];
      setParam(_param); //初始化聚合维度
      const timeSelect =
        _issueStatus &&
        _issueStatus?.length > 0 &&
        _issueStatus.every((item: any) => !item.hasOwnProperty('label'))
          ? _issueStatus
          : issueStatusOption.map((item: { value: any }) => item.value);
      const postData = {
        marketId: regionCode,
        contractTypes: timeSelect,
        startDate: _startDate,
        endDate: _endDate,
        point: _pointNum === '24' ? '24' : '96',
        tag: _tag,
        stationIds: _unit,
        order: _param,
        allContractTypes: allContractTypes,
      };
      _fetchFile(postData);
    },
    { wait: 500 },
  );

  // 序列选择数据
  const getTimeOptions = async (data: any) => {
    const timeParams = {
      startDate: data.startDate || '',
      endDate: data.endDate || '',
      marketId: data.marketId || '',
      stationIds: data?.stationIds || [],
      tag: data.tag || '1',
    };
    const res = await getTimeTradeData(timeParams);
    if (res?.statusCode === HttpCode.SUCCESS) {
      const timeOptions = res?.data?.time || [];
      const noTimeOptions = res?.data?.noTime || [];
      setTimeOptions(timeOptions);
      setNoTimeOptions(noTimeOptions);
    }
  };

  //默认请求
  const defaultRequest = async (_stations: any, _regions: any) => {
    form.setFieldsValue({ region: _regions[0].value, unit: [] });
    const stationsIds = getStationOptions(_regions[0]?.children);

    const values = {
      date: dataInit,
      point: '24',
      issueStatus: [],
      tag: '1',
      unit: stationsIds,
    };
    setEchartsParam({
      ...values,
      timeOrder: '24',
    });
    //重新渲染表格数据
    _onFinish.run(values);
  };

  async function initDataPower(data = [] as any) {
    // 处理数据权限
    if (!data) {
      return;
    }
    const _stations = [] as any;
    const _rs = [] as any;
    data.map((x: any) => {
      // 省份
      _rs.push(x);
      (x?.children || []).map((y: any) => {
        // 公司
        (y?.children || []).map((z: any) => {
          // 场站
          _stations.push(z);
        });
      });
    });
    setFormValues({
      date: dataInit,
      unit: _stations.map((i: any) => i.stationId),
      tag: '1',
    });
    /* const timeParams = {
      startDate: dataInit && moment(dataInit[0]).format('YYYY-MM-DD'),
      endDate: dataInit && moment(dataInit[1]).format('YYYY-MM-DD'),
      marketId: _rs?.[0]?.marketId || '',
      stationIds: _stations?.map((i: any) => i.stationId),
      tag: form.getFieldValue('tag') || '1',
    };
    getTimeOptions(timeParams); */
    setRegionCode(_rs?.[0]?.marketId || '');
    setProvinceId(_rs?.[0]?.provinceId || '');
    setRegions(_rs);
    setStations(_stations);
    defaultRequest(_stations, _rs);
  }

  //切换省份
  const onRegionChange = (value: any, selectOptions: any) => {
    setRegionCode(selectOptions.marketId);
    setProvinceId(selectOptions.provinceId);
    form.setFieldsValue({
      unit: [],
    });
    getStationOptions(selectOptions.children);
  };

  //取出非合计行默认第一行 最后一个子维度 作为echarts的横坐标
  const _getXAXIS = (data: any, arr: any[]) => {
    const _temp: any[] = [];
    const recursion = (item: any, index: number): any[] => {
      _temp.push({
        tag: item[0]?.tag,
        title: item[0]?.title,
      });
      if (item[0]?.children instanceof Array && item.length > 0) {
        return recursion(item[0].children, index - 1);
      }
      return _temp;
    };
    return recursion(data, arr.length - 1);
  };

  const getClassName = () => {
    let classNameEcharts = styles.charts;
    let classNameTable = styles.table;
    if (isFullScreenEcharts) {
      classNameEcharts = `${styles.chartsFullWidth}`;
      classNameTable = `${styles.tableNoWidth}`;
    } else if (isFullScreenTable) {
      classNameEcharts = `${styles.chartsNoWidth}`;
      classNameTable = `${styles.tableFullWidth}`;
    }

    return {
      classNameEcharts,
      classNameTable,
    };
  };

  const confirm = useDebounceFn(
    () => {
      setVisible(false);
      form && form.submit();
    },
    { wait: 500 },
  );

  const handleVisibleChange = (newVisible?: boolean) => {
    const { date, unit } = form.getFieldsValue();
    if (date && unit.length > 0) {
      const days = date[1].diff(date[0], 'days') + 1;
      if (days * unit.length > 900) {
        setVisible(!!newVisible);
      } else {
        confirm.run();
      }
    } else if (!date || !unit.length) {
      setVisible(false);
    } else {
      confirm.run();
    }
  };

  /**建立echarts链接 */
  const getRef: any = (refData: any) => {
    const arr = [...state.refData];
    state.refData.push(refData);
    arr.push(refData);
    if (arr.length >= 2) {
      echarts.connect([...arr]);
    }
    setState({
      refData: arr,
    });
  };

  //根据父维度 筛选出图表所需数据  return:最后一个维度数组
  const _getFilterXAXIS = (data: any, arr: any[]): any[] => {
    const _echartsParam = _.cloneDeep(echartsParam);
    //取最后一个维度 第一行数据
    const recursion = (item: any, index: number): any[] => {
      const _item: any[] = [];
      item.forEach((t: any) => {
        if (t.title === '合计') return;
        _item.push(t);
      });
      let _temp: any[] = [];
      //如果已经是最后一个维度
      if (arr.length - 1 <= index) {
        return _item;
      }
      _item.forEach((t: any) => {
        t.title === _echartsParam[OPTION_KEY[arr[index]]] &&
          (_temp = recursion(t.children, index + 1));
      });
      return _temp;
    };
    return recursion(data, 0);
  };

  //获取默认第一行 根据传入维度递归获取数据
  const _getDimensionData = (data: any, deepIndex: number): any[] => {
    const newData = data.filter((i: any) => i.title !== '合计');
    if (deepIndex) {
      return _getDimensionData(
        newData[0].children.length ? newData[0].children : newData[1].children,
        deepIndex - 1,
      );
    }
    return newData;
  };

  //dealFunc
  const dealFunc = (tag: string, meta: string[], title: any, value: any[]) => {
    let obj: any = {};
    obj = {
      title:
        tag === '时点'
          ? pointConvert(title, form)
          : tag === '日期'
          ? title.replaceAll('-', '')
          : title,
      tag: tag,
    };

    meta.forEach((_t: string, _i: number) => {
      if (!value || !Array.isArray(value) || value[_i] === undefined) {
        obj[headerMap[_t]] = null;
      } else if (_i > 1) {
        obj[headerMap[_t]] = _t.includes('综合电价')
          ? value[_i]
          : _t.includes('电量')
          ? parseFloat(value[_i]).toFixed(3)
          : parseFloat(value[_i]).toFixed(2);
      } else {
        obj[headerMap[_t]] = value[_i];
      }
    });

    return obj;
  };

  const totalDealFunc = (tag: string, meta: string[], title: any, value: any[]) => {
    let obj: any = {};
    obj = {
      title: title,
      tag: tag,
    };
    meta.forEach((_t: string, _i: number) => {
      if (_i > 1) {
        obj[headerMap[_t]] = _t.includes('电量')
          ? parseFloat(value[_i]).toFixed(3)
          : parseFloat(value[_i]).toFixed(2);
      } else {
        obj[headerMap[_t]] = value[_i];
      }
    });
    obj.children = []; //合计行没有子维度
    return obj;
  };

  //处理表格数据 dataSource表格数据 postdata选项
  const getNewDataSource = (dataSource: any, order: any, selectedKeys: string[] = []) => {
    if (!dataSource) return [];
    const formatForTable = (item: any, optionName: any, index = 0) => {
      const arr: any[] = [];
      Object.entries(item).map((t: any) => {
        if (t[0] === 'total') {
          return;
        }
        //最后一个维度为数组
        if (t[1] instanceof Array) {
          arr.push(dealFunc(optionName[index], dataSource.meta, t[0], t[1]));
          return;
        }
        const obj = dealFunc(optionName[index], dataSource.meta, t[0], t[1].total);
        obj.children = formatForTable(t[1], optionName, index + 1);
        arr.push(obj);
      });
      arr.sort((a: any, b: any) => {
        if (optionName[index] === '交易单元') {
          return a.title.localeCompare(b.title, 'zh-CN');
        }
        //默认时点排序方式
        return a.title > b.title ? 1 : -1;
      });
      return arr;
    };
    // 添加合计行
    const result = [
      totalDealFunc(order[0], dataSource.meta, '合计', dataSource.data.total),
      ...formatForTable(dataSource.data, order),
    ];
    return result;
  };

  const flattenDeep = (list: any = [], selectedKeys: string[] = []) => {
    list?.forEach((l: any) => {
      // 默认选中
      if (l?.checkbox === 1 && l?.key) {
        selectedKeys.push(l.key);
      }
      l?.children?.length && flattenDeep(l.children, selectedKeys);
    });
    return selectedKeys;
  };

  const filterColumns = (list: string[] = []) => {
    const headerList: any = [];
    tableHead?.forEach((t) => {
      headerList.push(t);
    });
    if (Object.keys(tableData)?.length) {
      getNewDataSource(tableData, param, list);
    }
    setTableHeader(headerList);
  };

  async function _fetchFile(postdata: any) {
    const { order } = postdata;
    setParam(order);
    setListLoading(true);
    setTableDataSource([]);
    const res = await querySpotResumeAnalysisDetail(postdata).catch(() => {});
    const columnsRes = await getDynamicColumns({
      regionCode: provinceId,
      menuCode,
    });
    setListLoading(false);
    if (res.statusCode === HttpCode.SUCCESS) {
      let selectedKeys: any[] = [];
      selectedKeys = flattenDeep(columnsRes?.data || [], selectedKeys);
      filterColumns(selectedKeys);
      setTableData(res?.data || {});
      const data: any = getNewDataSource(res?.data, order, selectedKeys);
      setTableDataSource(data);
      setColumns(columnsRes?.data || []);
      if (data.length) {
        const _data = _.cloneDeep(data);
        //设置图表数据
        const _echarsData = _getXAXIS(_data.splice(1), SELECT_DATA);

        //设置父维度列表值
        setFilterUnitOptions(
          (form.getFieldValue('unit')?.length ? form.getFieldValue('unit') : optionAll).map(
            (t: any) => {
              const item = stations.find((_t: any) => t == _t.stationId);
              return {
                label: item.stationName,
                value: item.stationName,
              };
            },
          ),
        );
        setDateTime(form.getFieldValue('date'));

        const echartsParams = {
          date:
            order.includes('日期') &&
            moment(_echarsData.find((t) => t.tag === '日期').title).format('YYYYMMDD'),
          unit:
            order.includes('交易单元') && _echarsData.find((t) => t.tag === '交易单元').title + '',
          timeOrder:
            order.includes('时点') && form.getFieldValue('point') === '24' ? '0100' : '0015',
        };
        //设置父维度选择默认值【合约量价图】默认：第一个维度
        setEchartsParam(echartsParams);
      }
      onFetchSumarys(res?.data?.largeScreen);
    } else {
      message.error(res.message || '查询数据有误');
    }
  }

  // 导出数据
  const onexport = () => {
    if (!tableDataSource.length) return;
    const hasSave =
      buttonPermissions.filter(
        (item: any) => item.menuCode === 'LongTermQuotationTacticsExportButton',
      ).length > 0;
    if (!hasSave) {
      return TRMessage.info('请联系管理员获取相关权限');
    }
    const _date = exportParam.dateRange;
    const filename = `中长期策略复盘-${moment(_date[0]).format('YYYYMMDD')}_${moment(
      _date[1],
    ).format('YYYYMMDD')}`;

    // 合并单元格配置
    const params: any = {
      multiHeader: [],
      header: [''],
      data: [],
      merges: [
        'C1:I1',
        'J1:P1',
        'Q1:W1',
        'A1:A3',
        'B1:B3',
        'C2:C3',
        'D2:D3',
        'E2:E3',
        'F2:F3',
        'G2:G3',
        'H2:H3',
        'I2:I3',
        'J2:J3',
        'K2:K3',
        'L2:L3',
        'M2:M3',
        'N2:N3',
        'O2:O3',
        'P2:P3',
        'Q2:Q3',
        'R2:R3',
        'S2:S3',
        'T2:T3',
        'U2:U3',
        'V2:V3',
        'W2:W3',
      ],
      filename,
    };

    const data = tableDataSource;
    const dataFalt: any[] = [];

    data.map((x: any) => {
      dataFalt.push({
        ...x,
        onlineQuantity: x.onlineQuantity,
      });
      (x?.children || []).map((y: any) => {
        dataFalt.push({
          ...y,
          onlineQuantity: y.onlineQuantity,
        });
        (y?.children || []).map((z: any) => {
          dataFalt.push({
            ...z,
            onlineQuantity: z.onlineQuantity,
          });
          (z?.children || []).map((e: any) => {
            dataFalt.push({
              ...e,
              onlineQuantity: e.onlineQuantity,
            });
          });
        });
      });
    });

    const filterVal: string[] = ['title', 'onlineQuantity'];
    const multiHeader2 = [param[0], '上网电量'],
      multiHeader = ['交易单元', '上网电量'];

    tableHeader?.forEach((item: any) => {
      //第一级
      multiHeader.push(params.multiHeader.includes(item.parentName) ? '' : item.parentName);
      //第二级
      multiHeader2.push(
        item.secondParentName
          ? item.secondParentName === multiHeader2[multiHeader2.length - 1]
            ? ''
            : item.secondParentName || ''
          : item.name,
      );
      //最后一级
      params.header.push(item.name);
      filterVal.push(item.field);
    });

    params.multiHeader = [multiHeader, multiHeader2];
    params.data = formatJson(filterVal, dataFalt);
    export_json_to_excel(params);
  };

  const calcDeviationPrice = (
    balanceQuantity: number,
    balancePrice: number,
    avgPrice: number,
  ): number => {
    if (!balanceQuantity || !balancePrice || !avgPrice) return 0;
    // 四舍五入保留2位小数
    return Number((balanceQuantity * (balancePrice - avgPrice)).toFixed(2));
  };

  //根据筛选参数 重绘图表
  const repaint = () => {
    const _echarsData = _getFilterXAXIS(tableDataSource, param);
    if (!_echarsData?.length || !tableDataSource.length) {
      setEchartsTariffData({});
      setEchartsIncomeData({});
      setEchartsPriceData({});
      return;
    }
    const _xaxis = _echarsData.map((t) => t.title);
    setEchartsTariffData({
      XAXIS: _xaxis,
      DeviationCost: _echarsData.map((t) => t.deviationCost),
      RecycleDeviationCost: _echarsData.map((t) => t.recycleDeviationCost),
      FeeDeductionCost: _echarsData.map((t) => t.feeDeductionCost),
      DeductionPrice: _echarsData.map(
        // (t) => (t.balanceQuantity * t.balancePrice) - (t.balanceQuantity * t.avgPrice),
        (t) => calcDeviationPrice(t.balanceQuantity, t.balancePrice, t.avgPrice),
      ),
    });
    setEchartsIncomeData({
      XAXIS: _xaxis,
      ActualBComprehensivePrice: _echarsData.map((t) => t.actualBComprehensivePrice),
      SimulateAActualComprehensivePrice: _echarsData.map(
        (t) => t.simulateAActualComprehensivePrice,
      ),
      ActualBActualAAvgPrice: _echarsData.map((t) => t.actualBActualAAvgPrice),
      SimulateAAvgPrice: _echarsData.map((t) => t.simulateAAvgPrice),
      AvgPrice: _echarsData.map((t) => t.avgPrice),
      BalancePrice: _echarsData.map((t) => t.balancePrice),
    });
    setEchartsPriceData({
      XAXIS: _xaxis,
      ActualBTotalLongTermQuantity: _echarsData.map((t) => t.actualBTotalLongTermQuantity),
      SimulateATotalLongTermQuantity: _echarsData.map((t) => t.simulateATotalLongTermQuantity),
      BalanceQuantity: _echarsData.map((t) => t.balanceQuantity),
      OnlineQuantity: _echarsData.map((t) => t.onlineQuantity),
    });
  };

  const getTimeOptionsDebounced = useDebounceFn(
    (params) => {
      getTimeOptions(params);
    },
    { wait: 300 },
  );

  React.useEffect(() => {
    if (tableDataSource.length > 0) {
      repaint();
    }
  }, [echartsParam]);

  useEffect(() => {
    if (reTime) {
      setIssueStatusOption(issueStatusOption);
      setAllContractTypes(allContractTypes);
    }
  }, [reTime, issueStatusOption, allContractTypes]);

  useEffect(() => {
    const { date, unit, tag } = formValues;
    if (!date || !unit?.length || !tag) return;
    const timeParams = {
      startDate: date && moment(date[0]).format('YYYY-MM-DD'),
      endDate: date && moment(date[1]).format('YYYY-MM-DD'),
      marketId: regionCode,
      stationIds: unit,
      tag,
    };
    getTimeOptionsDebounced.run(timeParams);
  }, [formValues, regionCode]);

  const _onReset = useDebounceFn(
    () => {
      form.resetFields();
      const regionId = form.getFieldValue('region') ?? '';
      onRegionChange(
        regionId,
        regions?.find((i) => i.marketId === regionId),
      );
      setTableDataSource([]);
      setIssueStatusOption([]);
      setAllContractTypes([]);
      // setIssueStatusOption(selectTimeOptions);
      setReTime(new Date().getTime()); //重置时间戳
      init();
      // defaultRequest(stations, regions);
    },
    { wait: 500 },
  );

  const issueStatusChange = (e: any, aContractTypes: any) => {
    setIssueStatusOption(e);
    setAllContractTypes(aContractTypes);
    form?.setFieldsValue({ issueStatus: e });
  };

  const _renderHeader = () => {
    const initialValues = () => {
      return {
        region: regions[0].value,
        date: dataInit,
        issueStatus: issueStatusOption,
        point: '24',
        tag: '1',
      };
    };
    return (
      <div className={styles.header}>
        <Form
          form={form}
          initialValues={initialValues()}
          className={styles.formStyles}
          onFinish={_onFinish.run}
          onValuesChange={(changedValues, allValues) => {
            if (changedValues.date || changedValues.unit || changedValues.tag) {
              setFormValues({
                date: allValues.date,
                unit: allValues.unit,
                tag: allValues.tag,
              });
            }
          }}
        >
          <Form.Item name="region" className={styles.cell_item}>
            <Select
              options={regions}
              style={{ width: 200 }}
              placeholder="请选择交易中心"
              showSearch={true}
              onChange={(e, e2) => {
                onRegionChange(e, e2);
              }}
            />
          </Form.Item>
          <Form.Item name="unit" className={styles.cell_item}>
            <TjStation options={stationTree} />
          </Form.Item>
          <Form.Item
            name="date"
            className={styles.cell_item}
            rules={[{ required: true, message: '请选择日期' }]}
          >
            <RangePicker className={styles.select_date} format={'YYYYMMDD'} separator={'-'} />
          </Form.Item>
          <Form.Item name="issueStatus" className={styles.cell_item}>
            <TjSequenceSelect
              statusOption={issueStatusOption}
              issueStatusChange={issueStatusChange}
              timeOptions={timeOptions}
              noTimeOptions={noTimeOptions}
              reTime={reTime}
            />
          </Form.Item>
          <Form.Item name="point" className={styles.cell_item} style={{ display: 'none' }}>
            <div className={styles.tag}>
              <Pointer
                options={[
                  { label: '24', value: '24' },
                  { label: '96', value: '96' },
                ]}
                data={'24'}
              />
            </div>
          </Form.Item>
          <Form.Item name="tag" className={styles.cell_item}>
            <div className={styles.tag}>
              <Pointer
                options={[
                  { label: '测算数据', value: '1' },
                  { label: '结算数据', value: '2' },
                ]}
                data={'1'}
              />
            </div>
          </Form.Item>
          <Popconfirm
            title="您选择的数据量较大，可能延长加载时间或引起页面崩溃，是否确认查询？"
            visible={visible}
            onVisibleChange={handleVisibleChange}
            onConfirm={() => confirm.run()}
            onCancel={() => setVisible(false)}
            okText="确认"
            cancelText="取消"
          >
            <Button className={styles.submit} type="primary" htmlType="submit">
              查询
            </Button>
          </Popconfirm>
          <Button className={styles.reset} htmlType="reset" onClick={_onReset.run} ghost>
            重置
          </Button>
          <div
            className={`${styles.import} ${!tableDataSource.length && styles.disabled}`}
            onClick={onexport}
          >
            <UploadOutlined style={{ fontSize: '0.12rem' }} />
            导出
          </div>
        </Form>
      </div>
    );
  };
  //展板
  const _renderBoard = () => {
    if (!tableDataSource.length) return;
    return (
      <div className={styles.board}>
        <Title data={sumaryData} />
      </div>
    );
  };

  //表格图表内容区域渲染
  const _renderContent = () => {
    if (listLoading)
      return (
        <div className={styles.emty}>
          <PageLoading />
        </div>
      );
    // if (dataLock) return <div className={styles.emty}><Empty image={img_lock} imageStyle={{ height: '150px' }} description="您没有相关权限，请联系管理员" /></div>;
    if (!tableDataSource.length) return <TRDefault type={'empty'} />;
    /*获取设置选择器下拉列表项*/
    const pointOptions =
      param.includes('时点') && param.indexOf('时点') < param.length - 1
        ? _getDimensionData(tableDataSource, param.indexOf('时点')).map((t) => ({
            label: t.title,
            value: t.title,
          }))
        : [];
    //重新聚合
    const _polymerize = async (options: any) => {
      setParam(options);
      //重新渲染表格数据
      const _formData: any = form.getFieldsValue(true),
        _date = _formData.date,
        _startDate = _date && moment(_date[0]).format('YYYY-MM-DD'),
        _endDate = _date && moment(_date[1]).format('YYYY-MM-DD'),
        _pointNum = _formData.point,
        _issueStatus = _formData.issueStatus,
        _tag = _formData.tag,
        _unit = _formData.unit;

      const timeSelect =
        _issueStatus && _issueStatus?.length > 0
          ? _issueStatus.map((item: { label: string; value: string }) =>
              item.label ? item.value : item,
            )
          : issueStatusOption.map((item: { value: any }) => item.value);
      const postData = {
        marketId: regionCode,
        contractTypes: timeSelect,
        startDate: _startDate,
        endDate: _endDate,
        point: _pointNum === '24' ? '24' : '96',
        tag: _tag,
        stationIds: _unit,
        order: options,
        allContractTypes: allContractTypes,
      };
      /* const test = {
        marketId: regionCode,
        contractTypes: timeSelect,
        endDate: '2025-03-09',
        order: options,
        orderType: '24',
        startDate: '2025-03-01',
        stationIds: [14083003, 14014006, 14000001],
        tag: '1',
        allContractTypes: allContractTypes,
      }; */
      await _fetchFile(postData);
    };

    const _selectUnitOnChange = (value: any) => {
      setEchartsParam({
        ...echartsParam,
        unit: value,
      });
    };

    const _selectDateOnChange = (value: any) => {
      setEchartsParam({
        ...echartsParam,
        date: value.format('YYYYMMDD'),
      });
    };

    const _selectPointOnChange = (value: any) => {
      setEchartsParam({
        ...echartsParam,
        timeOrder: value,
      });
    };

    //控制日历可选范围
    const disabledDate = (current: any) => {
      const _date = dateTime;
      return (current && current < _date[0].startOf('day')) || current > _date[1].endOf('day');
    };

    return (
      <>
        <div className={[styles.leftBox, getClassName().classNameTable].join(' ')}>
          <div
            className={styles.leftArrow}
            onClick={() => {
              setIsFullScreenTable(!isFullScreenTable);
            }}
          >
            {isFullScreenTable ? <CaretLeftOutlined /> : <CaretRightOutlined />}
          </div>
          <DimensionalSort
            reSize={reSize}
            optionsArray={SELECT_DATA}
            option={param}
            onClick={_polymerize}
            columns={columns}
            menuCode={menuCode}
            regionCode={regionCode}
            filterColumns={filterColumns}
          />
          <BaseTable tableData={tableDataSource} tableHeader={tableHeader} text={param[0]} />
        </div>
        {
          <div className={[styles.rightBox, getClassName().classNameEcharts].join(' ')}>
            <div className={styles.filter_group}>
              <div className={styles.flex}>
                {param.map((t: any, i: number) => {
                  if (t === '交易单元' && param[param.length - 1] !== '交易单元') {
                    {
                      return (
                        <Select
                          key={i}
                          className={styles.filter_unit}
                          style={{ marginLeft: i === 0 ? 0 : '.16rem' }}
                          showSearch
                          placeholder="选择交易单元"
                          onChange={_selectUnitOnChange}
                          value={echartsParam.unit}
                          options={filterUnitOptions}
                          filterOption={(input, option) => {
                            return (option?.label as unknown as string)
                              .toLowerCase()
                              .includes(input.toLowerCase());
                          }}
                        />
                      );
                    }
                  }
                  if (t === '日期' && param[param.length - 1] !== '日期') {
                    {
                      return (
                        <DatePicker
                          key={i}
                          onChange={_selectDateOnChange}
                          inputReadOnly
                          allowClear={false}
                          className={styles.filter_date}
                          style={{ marginLeft: i === 0 ? 0 : '.16rem' }}
                          value={moment(echartsParam.date)}
                          format={monthFormat}
                          disabledDate={disabledDate}
                        />
                      );
                    }
                  }
                  if (t === '时点' && param[param.length - 1] !== '时点') {
                    {
                      return (
                        <Select
                          key={i}
                          className={styles.filter_point}
                          style={{ marginLeft: i === 0 ? 0 : '.16rem' }}
                          placeholder="选择时点"
                          onChange={_selectPointOnChange}
                          value={echartsParam.timeOrder}
                          options={pointOptions}
                        />
                      );
                    }
                  }
                })}
              </div>
            </div>
            <div className={styles.content_box}>
              <div
                className={styles.rightArrow}
                onClick={() => {
                  setIsFullScreenEcharts(!isFullScreenEcharts);
                }}
              >
                {isFullScreenEcharts ? <CaretRightOutlined /> : <CaretLeftOutlined />}
              </div>
              {!echartsTariffData?.XAXIS?.length ? (
                <div className={styles.emty}>
                  <TRDefault type="emptysm" />
                </div>
              ) : (
                <>
                  <div className={styles.title} style={{ paddingTop: 0 }}>
                    偏差分析 <span className={styles.label}>单位：元</span>
                  </div>
                  <div style={{ flex: 1, minHeight: '200px' }}>
                    <ChartDealTariff
                      isFullScreenEcharts={isFullScreenEcharts}
                      data={echartsTariffData}
                      scale={reSize / 100}
                      getRef={getRef}
                    />
                  </div>
                  <div className={styles.title}>
                    电价分析 <span className={styles.label}>单位：元/MWh</span>
                  </div>
                  <div style={{ flex: 1, minHeight: '200px' }}>
                    <ChartDealIncome
                      isFullScreenEcharts={isFullScreenEcharts}
                      data={echartsIncomeData}
                      scale={reSize / 100}
                      getRef={getRef}
                    />
                  </div>
                  <div className={styles.title}>
                    电量分析 <span className={styles.label}>单位: MWh</span>
                  </div>
                  <div style={{ flex: 1, minHeight: '200px' }}>
                    <ChartDealPrice
                      isFullScreenEcharts={isFullScreenEcharts}
                      data={echartsPriceData}
                      scale={reSize / 100}
                      getRef={getRef}
                    />
                  </div>
                </>
              )}
            </div>
          </div>
        }
      </>
    );
  };

  if (loading) return <PageLoading />;
  if (error) return <TRDefault type="error" message={error} />;
  if (!stations?.length) return <TRDefault type="lock" />;
  return (
    <>
      {_renderHeader()}
      {_renderBoard()}
      <div className={styles.content_body}>
        <div className={styles.content}> {_renderContent()}</div>
      </div>
    </>
  );
};
export default connect(({ global }: any) => ({
  menuCode: global.configure.menuCode,
  buttonPermissions: global.configure.buttonPermissions,
}))(NewMediumlongTermResetting);
